<?php

function copyListFromDb($twitter_username, $group_id) {
	global $twitter;
	global $MESSAGES;
	global $SETTINGS;
	
	$new_list = false;

	$connect = connectToDb();
	
	$query = sprintf("SELECT title FROM groups WHERE group_id = %s ",
					mysql_real_escape_string($group_id));
	$query.= "AND (del_flag <> 'd' OR del_flag IS NULL)";
					
	$result = mysql_query($query, $connect);
	$row = mysql_fetch_assoc($result);
	
	$group_name = $row['title'];
	
	$query = sprintf("SELECT user_id FROM group_members WHERE group_id = %s ",
					mysql_real_escape_string($group_id));
	$query.= "AND (del_flag <> 'd' OR del_flag IS NULL)";
					
	$result = mysql_query($query, $connect);
	
	$db_group_members = array();
	while ($row = mysql_fetch_assoc($result)) {
		array_push($db_group_members, $row['user_id']);
	}
	
	$params = array();
	$params['slug'] = $group_name;
	$params['owner_screen_name'] = $twitter_username;
	
	try {
		$list_info = $twitter->get_listsShow($params)->response;
		
		if ($list_info['description'] != $SETTINGS['LIST_DESCRIPTION'] || empty($list_info['description'])) {
			return $MESSAGES['COPY_LIST_ALREADY_EXIST'];
		}
		else {
			$list_members = $twitter->get_listsMembers($params)->response;
		}
	}
	catch (Exception $e) {
		$params = array();
		$params['name'] = $group_name;
		$params['description'] = $SETTINGS['LIST_DESCRIPTION'];
		$twitter->post_listsCreate($params);
		
		$new_list = true;
	}
	
	$to_add = array();
	$to_remove = array();
	
	$matches = array();
	
	if (!$new_list) {
		// データベースのメンバーと比較する
		
		foreach ($list_members['users'] as $member) {
			$id = $member['id'];
			$match = array_search($id, $db_group_members);
			
			if ($match !== false) {
				array_push($matches, $id);
			}
			else {
				array_push($to_remove, $id);
			}
		}
		
		$to_add = array_diff($db_group_members, $matches);	
	}
	else {
		$to_add = $db_group_members;
	}
	
	/***** グループにメンバーを追加 *****/
	$members = "";
	foreach ($to_add as $member) {
		$members .= $member . ",";
	}
	$members = substr($members,0,-1);
	
	$params = array();
	$params['slug'] = $group_name;
	$params['owner_screen_name'] = $twitter_username;
	$params['user_id'] = $members;
	
	try {
		$twitter->post_listsMembersCreate_all($params);
	}
	catch (Exception $e) {
	die(var_dump($params));
		return $MESSAGES['COPY_LIST_ERROR_ADD'] . ":" . $e->getMessage();
	}

	/***** グループにメンバーを追加 *****/
	try {
		foreach ($to_remove as $member) {
			$params = array();
			$params['slug'] = $group_name;
			$params['owner_screen_name'] = $twitter_username;
			$params['user_id'] = $member;
		
			$twitter->post_listsMembersDestroy($params);
		}
	}
	catch (Exception $e) {
		return $MESSAGES['COPY_LIST_ERROR_REMOVE'];
	}
	
	if (empty($to_add) && empty($to_remove)) {
		return false;
	}
	else {
		return true;
	}
}

?>